package fan.project3_pksystem.Module;

import com.fasterxml.jackson.databind.ObjectMapper;
import fan.project3_pksystem.WebSocket.WSResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

@Component
public class FindPlayerQueue {
    @Autowired
    OnLinePlayers onlinePlayers;
    final Queue<UserInfo> lv1queue = new LinkedList<>();
    final Queue<UserInfo> lv2queue = new LinkedList<>();
    final Queue<UserInfo> lv3queue = new LinkedList<>();
    @Autowired
    private ObjectMapper objectMapper;

    public void add(UserInfo userInfo) {
        if (userInfo.getScore() < 100) {

            synchronized (lv1queue) {
                lv1queue.add(userInfo);
                lv1queue.notify();
            }
            System.out.println(userInfo.getUserName() + "加入低级匹配队列");

        } else if (userInfo.getScore() < 200) {

            synchronized (lv2queue) {
                lv2queue.add(userInfo);
                lv2queue.notify();
            }
            System.out.println(userInfo.getUserName() + "加入中级匹配队列");

        } else if (userInfo.getScore() < 300) {
            synchronized (lv3queue) {
                lv3queue.add(userInfo);
                lv3queue.notify();
            }
            System.out.println(userInfo.getUserName() + "加入高级匹配队列");
        }
    }

    public void remove(UserInfo userInfo) {
        if (userInfo.getScore() < 100) {
            lv1queue.remove(userInfo);
        } else if (userInfo.getScore() < 200) {
            lv2queue.remove(userInfo);
        } else if (userInfo.getScore() < 300) {
            lv3queue.remove(userInfo);
        }
        System.out.println(userInfo.getUserName() + "退出匹配队列");
    }

    FindPlayerQueue() {
        new Thread(() -> {
            while (true) {
                matchPlayer(lv1queue);
            }
        }).start();
        new Thread(() -> {
            while (true) {
                matchPlayer(lv2queue);
            }
        }).start();
        new Thread(() -> {
            while (true) {
                matchPlayer(lv3queue);
            }
        }).start();
    }


    @Autowired
    GameRoomManager gameRoomManager;
    private void matchPlayer(Queue<UserInfo> queue) {
        synchronized (queue) {
//            为什么用while?  因为得等满足至少2个人在队列中才能匹配,0个人和1个人都是没有意义的
            while (queue.size() < 2) {
                try {
                    queue.wait();
                } catch (InterruptedException e) {
                    System.out.println("匹配队列休眠状态异常");
                }

            }
            UserInfo user1 = queue.poll();
            UserInfo user2 = queue.poll();
//        防止自己匹配自己
            if (user1 == user2) {
                queue.offer(user1);
            }
//        玩家已离线的处理
            WebSocketSession session1 = onlinePlayers.getHubOl(user1.getId());
            WebSocketSession session2 = onlinePlayers.getHubOl(user2.getId());

            if (session1 == null) {
                queue.offer(user2);
                return;
            }
            if (session2 == null) {
                queue.offer(user1);
                return;
            }
            if (session2==session1){
                System.out.println("匹配时两个会话相同");
            }

            System.out.println("匹配成功");
            WSResponse wsResponse = new WSResponse();
            wsResponse.setCode("SUCCESS");
            wsResponse.setMessage("find success");
            System.out.println((user1.getUserName() + "和" + user2.getUserName() + "匹配成功了"));

            try {

                String message = objectMapper.writeValueAsString(wsResponse);
                synchronized (session1){
                    session1.sendMessage(new TextMessage(message));
                    session1.close();
                }
                synchronized (session2){
                    session2.sendMessage(new TextMessage(message));
                    session2.close();
                }


//            新建一个空房间,并将两个玩家的id指向该房间的uuid

                gameRoomManager.add(new GameRoom(),user1,user2);


            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("匹配成功时遇到错误");
            }


        }
    }


}
